<template>
	<div :id="divId">
		<textarea name="fortressEditor007" :id="id" rows="10" cols="80"></textarea>
		<resource-select ref="ResourceSelect" model-name="form" type="image" @choosed="onSelectChoose"></resource-select>
	</div>
</template>

<script>
import ResourceSelect from "@/components/resource-select.vue"

export default {
	name: "FortressEditor",
	props: ["value"],
	data() {
		return {
			id: "fk" + parseInt(Math.random() * 10000),
			divId: "fe" + parseInt(Math.random() * 10000),
			ckEditor: null,
		}
	},
	mounted() {
		const self = this
		//渲染编辑器
		const CKEDITOR = window.CKEDITOR
		this.ckEditor = CKEDITOR.replace(this.id)
		//设置初始值
		CKEDITOR.instances[this.id].setData(this.value ? this.value : "")
		//监听内容变化
		CKEDITOR.instances[this.id].on("change", function() {
			self.$emit("input", CKEDITOR.instances[self.id].getData())
		})
		CKEDITOR.instances[this.id].on("afterPaste", function() {
			setTimeout(() => {
				self.$emit("input", CKEDITOR.instances[self.id].getData())
			}, 500)
		})
		window.__CKEditor__Handle__ = () => {
			this.$refs.ResourceSelect.openDialog()
		}
	},
	methods: {
		getText() {
			return CKEDITOR.instances[this.id].document.getBody().getText()
		},

		onSelectChoose(checked) {
			let url = this.urlFmt(checked)
			const str = `<img src="${url}" />`
			CKEDITOR.instances[this.ckEditor.name].insertHtml(str)

			this.$emit("input", CKEDITOR.instances[this.id].getData())
		},
		urlFmt(row) {
			//row.ossPlatform 不为空 代表是资源库选择的  判断 本地存储拼接域名/oss直接用路径
			if (row.ossPlatform) {
				return row.resourceUrl
			} else {
				//row.ossPlatform 不为空 代表是直接上传的,直接取上传接口返回的url
				return row.url
			}
		},
	},
	watch: {
		value: {
			handler(val) {
				const CKEDITOR = window.CKEDITOR
				let self = this
				let ckData = val != null ? val : ""
				if (CKEDITOR.instances[this.id] && ckData != CKEDITOR.instances[self.id].getData()) {
					// CKEDITOR.instances[this.id].setData(ckData);
					let timmer = setInterval(function() {
						if (
							document.getElementById(self.divId).getElementsByTagName("iframe") &&
							document.getElementById(self.divId).getElementsByTagName("iframe").length > 0
						) {
							let a = document.getElementById(self.divId).getElementsByTagName("iframe")[0].contentWindow.document
							a.body.innerHTML = ckData
							clearInterval(timmer)
						}
					}, 100)
				}
			},
			immediate: false,
		},
	},
	components: {
		ResourceSelect,
	},
}
</script>
